﻿Imports XL.Common
Imports XL.Common.Utils
Imports XL.Win
Imports XL.Win.Utils
Imports System.Threading

Namespace Utils

    Public Class MainForm
        Inherits XL.Win.Window.BaseMainForm

        Private WithEvents _bizAgent As New MainformAgent(Me)
#Region " Windows Auto Generated Code"

        Public Sub New()
            MyBase.New()

            '该调用是 Windows 窗体设计器所必需的。     
            InitializeComponent()

            '在 InitializeComponent() 调用之后添加任何初始化 

        End Sub

        '窗体重写 dispose 以清理组件列表。 
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub
        Public WithEvents SerialPort_Phone As System.IO.Ports.SerialPort
        Friend WithEvents LinkLabel_IncomingCall As System.Windows.Forms.LinkLabel

        'Windows 窗体设计器所必需的  
        Private components As System.ComponentModel.IContainer

        '注意: 以下过程是 Windows 窗体设计器所必需的   
        '可以使用 Windows 窗体设计器修改此过程。 
        '不要使用代码编辑器修改它。  
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container
            Me.SerialPort_Phone = New System.IO.Ports.SerialPort(Me.components)
            Me.LinkLabel_IncomingCall = New System.Windows.Forms.LinkLabel
            Me.Panel_TopImage.SuspendLayout()
            CType(Me.PanelControl_TopRange, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.PanelControl_TopRange.SuspendLayout()
            Me.SuspendLayout()
            '
            'Timer_CheckAlert
            '
            '
            'LabelControl_FormTitle
            '
            Me.LabelControl_FormTitle.Appearance.Font = New System.Drawing.Font("SimSun", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.LabelControl_FormTitle.Appearance.ForeColor = System.Drawing.Color.White
            Me.LabelControl_FormTitle.Appearance.Options.UseFont = True
            Me.LabelControl_FormTitle.Appearance.Options.UseForeColor = True
            Me.LabelControl_FormTitle.Location = New System.Drawing.Point(252, 8)
            Me.LabelControl_FormTitle.Size = New System.Drawing.Size(0, 16)
            '
            'Panel_TopImage
            '
            Me.Panel_TopImage.Size = New System.Drawing.Size(247, 53)
            '
            'LabelControl_SystemTitle
            '
            Me.LabelControl_SystemTitle.Appearance.Font = New System.Drawing.Font("Arial", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.LabelControl_SystemTitle.Appearance.ForeColor = System.Drawing.Color.Black
            Me.LabelControl_SystemTitle.Appearance.Options.UseFont = True
            Me.LabelControl_SystemTitle.Appearance.Options.UseForeColor = True
            Me.LabelControl_SystemTitle.Location = New System.Drawing.Point(53, 20)
            Me.LabelControl_SystemTitle.Size = New System.Drawing.Size(180, 21)
            Me.LabelControl_SystemTitle.Visible = False
            '
            'Label_Clock
            '
            Me.Label_Clock.Location = New System.Drawing.Point(818, 2)
            '
            'PanelControl_TopRange
            '
            Me.PanelControl_TopRange.Appearance.BackColor = System.Drawing.Color.Transparent
            Me.PanelControl_TopRange.Appearance.Options.UseBackColor = True
            Me.PanelControl_TopRange.Controls.Add(Me.LinkLabel_IncomingCall)
            Me.PanelControl_TopRange.Location = New System.Drawing.Point(0, 55)
            Me.PanelControl_TopRange.LookAndFeel.UseDefaultLookAndFeel = False
            Me.PanelControl_TopRange.Size = New System.Drawing.Size(1016, 53)
            Me.PanelControl_TopRange.Controls.SetChildIndex(Me.LinkLabel_IncomingCall, 0)
            Me.PanelControl_TopRange.Controls.SetChildIndex(Me.Panel_TopImage, 0)
            Me.PanelControl_TopRange.Controls.SetChildIndex(Me.LabelControl_FormTitle, 0)
            Me.PanelControl_TopRange.Controls.SetChildIndex(Me.Label_Clock, 0)
            '
            'DockPanel_LeftMenu
            '
            Me.DockPanel_LeftMenu.Location = New System.Drawing.Point(0, 108)
            Me.DockPanel_LeftMenu.Options.AllowFloating = False
            Me.DockPanel_LeftMenu.Size = New System.Drawing.Size(200, 508)
            '
            'SerialPort_Phone
            '
            '
            'LinkLabel_IncomingCall
            '
            Me.LinkLabel_IncomingCall.ActiveLinkColor = System.Drawing.Color.Gold
            Me.LinkLabel_IncomingCall.AutoSize = True
            Me.LinkLabel_IncomingCall.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.LinkLabel_IncomingCall.LinkColor = System.Drawing.Color.LawnGreen
            Me.LinkLabel_IncomingCall.Location = New System.Drawing.Point(253, 38)
            Me.LinkLabel_IncomingCall.Name = "LinkLabel_IncomingCall"
            Me.LinkLabel_IncomingCall.Size = New System.Drawing.Size(85, 13)
            Me.LinkLabel_IncomingCall.TabIndex = 5
            Me.LinkLabel_IncomingCall.TabStop = True
            Me.LinkLabel_IncomingCall.Text = "来电显示操作"
            Me.LinkLabel_IncomingCall.Visible = False
            Me.LinkLabel_IncomingCall.VisitedLinkColor = System.Drawing.Color.LawnGreen
            '
            'MainForm
            '
            Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 12.0!)
            Me.ClientSize = New System.Drawing.Size(1016, 642)
            Me.Name = "MainForm"
            Me.Text = ""
            Me.Panel_TopImage.ResumeLayout(False)
            CType(Me.PanelControl_TopRange, System.ComponentModel.ISupportInitialize).EndInit()
            Me.PanelControl_TopRange.ResumeLayout(False)
            Me.PanelControl_TopRange.PerformLayout()
            Me.ResumeLayout(False)
            Me.PerformLayout()

        End Sub

#End Region

        Public SV_TRANSACTING_INCOMING_CALL_TYPE As Integer
        Public SV_TRANSACTING_INCOMING_CALL_FORM As Component.BaseForm

        Protected Overrides ReadOnly Property GetFormByTypeName(ByVal formTypeName As String) As XL.Win.Component.BaseForm
            Get

                Dim appendFormType As Type = Type.GetType(formTypeName)
                Dim args As Object() = {Me.TransactRequestHandle, 0}
                Dim result As XL.Win.Component.BaseForm = CType(Activator.CreateInstance(appendFormType, args), XL.Win.Component.BaseForm)

                Return result

            End Get
        End Property

        Protected Overrides Sub BeforeLogout()
            MyBase.BeforeLogout()


        End Sub

        Protected Overrides Sub DoTasksOnMinite()
            Me._bizAgent.DoRequest(MainformAgent.Affairs.UpdateIncomingStatus, False)
        End Sub

        Protected Overrides ReadOnly Property GetAlertForm() As System.Collections.Hashtable
            Get

                Dim result As New Hashtable

                'If Facade.OpCheck.GetCheckValue() = True Then  

                '    result.Add(Decls.ALERT_TITLE_UTLD,"RExpClient.Manifest.M_04_00101")  

                'End If  

                'If Facade.OpCheck.GetCheckValue() = True Then   

                '    result.Add(Decls.ALERT_TITLE_UTLD,"RExpClient.Manifest.M_04_00201")  

                'End If  

                'If Facade.OpCheck.GetCheckValue() = True Then 

                '    result.Add(Decls.ALERT_TITLE_UTLD,"RExpClient.Manifest.M_04_00301")  

                'End If  

                'If Facade.OpCheck..GetCheckValue() = True Then

                '    result.Add(Decls.ALERT_TITLE_UTLD,"RExpClient.Manifest.M_04_00401")  

                'End If  

                'If Facade.OpCheck..GetCheckValue() = True Then     

                '    result.Add(Decls.ALERT_TITLE_UTLD,"RExpClient.Manifest.M_04_00501")  

                'End If  


                Return result
            End Get
        End Property


        Private Sub _bizAgent_Responded(ByVal responseResult As XL.Win.Component.BaseAgent.AgentResponse) Handles _bizAgent.Responded

            Dim operResult As String = CommTK.FString(responseResult.GetValue(WinDecl.RVN_SUCCEED))

            '    
            '操作不成功的情况下, 用出对话框报告操作不成功的原因  
            '-------------------------------------------------------------------   

            If operResult <> String.Empty Then
                XL.Win.Window.XLMessageBox.ShowMessage(operResult, Window.XLMessageBox.MessageType.Wrong, MessageBoxButtons.OK)


                Select Case Me._bizAgent.AffairOf(responseResult.ResponseTitle)              'transaction cases under error  



                End Select


                Return
            End If

            '    
            '操作成功的情况下, 继续下面的成功后处理  
            '-------------------------------------------------------------------   

            Select Case Me._bizAgent.AffairOf(responseResult.ResponseTitle)

                Case MainformAgent.Affairs.CheckAlerts

                    Me.DoPublicDisplayAlerts()

                Case MainformAgent.Affairs.UpdateIncomingStatus
                    Me.Invoke(New XL.Win.SubTransaction(AddressOf Me.DoPublicCheckCallTransactionFormType))
            End Select
        End Sub
        Private Sub Timer_CheckAlert_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_CheckAlert.Tick

            Me._bizAgent.DoRequest(MainformAgent.Affairs.CheckAlerts, False)

            If CommTK.FBoolean(SysInfo.ReadLocalSysInfo(CommDecl.XLSLVN_IS_CENTRAL_INFORMATION_DISTRIBUTER)) = True Then
                Me._bizAgent.DoRequest(MainformAgent.Affairs.SendMessages, False)
                Me._bizAgent.DoRequest(MainformAgent.Affairs.UpdateBizData, False)
            End If

        End Sub

        Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            If Me.SerialPort_Phone.IsOpen = True Then
                Me.SerialPort_Phone.Close()
            End If
        End Sub

        Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If CommTK.FBoolean(SysInfo.ReadLocalSysInfo(RExpXService.Decls.LVN_LISTEN_INCOMING_CALLS)) = True Then
                Me.DoPrivateInitModem()
            End If

            Utils.TK.ReloadCacheIncomingCallList()
            Me._bizAgent.DoRequest(MainformAgent.Affairs.UpdateIncomingStatus, True)
            Me.HideNotifyIcon = False
            Me.RestoreSkin()
        End Sub

        Private Sub DoPrivateInitModem()


            If Me.SerialPort_Phone.IsOpen = True Then
                Me.SerialPort_Phone.Close()
            End If

            Me.SerialPort_Phone.PortName = String.Format("COM{0}", SysInfo.ReadLocalSysInfo(RExpXService.Decls.LVN_LISTEN_PHONE_COM_PORT))
            If Me.SerialPort_Phone.IsOpen = True Then
                Me.SerialPort_Phone.Close()
            End If
            Try


                Me.SerialPort_Phone.Open()
                Select Case SysInfo.ReadLocalSysInfo(RExpXService.Decls.LVN_MODEM_AT_MODE)
                    Case "#"
                        Me.SerialPort_Phone.Write("AT#CID=1" + vbCr + "ATS0=2" + vbCr)
                    Case Else
                        Me.SerialPort_Phone.Write("AT+VCID=1" + vbCr + "ATS0=2" + vbCr)
                End Select
                Threading.Thread.Sleep(1000)
                'Me.SerialPort_Phone.WriteLine("ATS0=2")
                'Me.SerialPort_Phone.BaudRate=

                CommTK.OutputBizLog("ATAction", "SerialPort_Phone_DataReceived", "Me.SerialPort_Phone.Write(""AT+VCID=1"")---  Done")
                Me.ShowStatusMessage(StatusMessageIcon.Info, RExpXService.Decls.MSG_STATUS_0001, Me.SerialPort_Phone.PortName)

            Catch ex As Exception

                Me.ShowStatusMessage(StatusMessageIcon.Alert, ex.Message)
                Me.DoPublicShowPhoneListenerLink(RExpXService.Decls.TEXT_0011)

            End Try


        End Sub

        Public Sub DoPublicShowPhoneListenerLink(ByVal text As String, ByVal ParamArray args As Object())

            If text.Trim.Length = 0 Then
                Me.LinkLabel_IncomingCall.Visible = False
            End If

            Me.LinkLabel_IncomingCall.Visible = True
            Me.LinkLabel_IncomingCall.Text = CommTK.GetTranslatedString(text, args)

        End Sub

        Private Sub SerialPort_Phone_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort_Phone.DataReceived



            Dim receivingString As String = String.Empty
            Dim modemReceiveString As String = String.Empty
            
            Try
                Me.SerialPort_Phone.ReceivedBytesThreshold = Me.SerialPort_Phone.ReadBufferSize
                While True
                    receivingString = Me.SerialPort_Phone.ReadExisting()
                    If String.Equals(receivingString, String.Empty) Then
                        Exit While
                    Else
                        modemReceiveString += receivingString
                        Application.DoEvents()
                        Thread.Sleep(100)
                    End If
                End While
                modemReceiveString = modemReceiveString.Replace(" ", String.Empty)
                'strCollect = strCollect.Replace("", String.Empty)
                'strCollect = strCollect.Replace("", String.Empty)
                'strCollect = strCollect.Replace("", String.Empty)

                'If Not Me.bIsHandleCom Then
                '    Me.bIsHandleCom = True
                '    mReceiveData = strCollect
                '    RaiseEvent ReceiveDataParserEvent(mReceiveData)
                '    If ThreadReceiveParser IsNot Nothing AndAlso Not ThreadReceiveParser.IsAlive Then
                '        ThreadReceiveParser.Start()
                '    End If

                'End If
            Catch ex As Exception
                MessageBox.Show(Me, ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error])
            Finally
                Me.SerialPort_Phone.ReceivedBytesThreshold = 1
            End Try
            Console.WriteLine(modemReceiveString)

            CommTK.OutputBizLog("ATAction", "SerialPort_Phone_DataReceived", modemReceiveString)
            If modemReceiveString.Contains("NMBR=") = True Then

                Dim numberIndex = modemReceiveString.IndexOf("NMBR=") + 5
                Dim numberBuilder As New LineStrBuilder
                Dim numberChar As String
                Do While numberIndex < modemReceiveString.Length - 1
                    numberChar = modemReceiveString.Substring(numberIndex, 1)
                    If CommTK.IsNumericValue(numberChar) = False Then
                        Exit Do
                    End If

                    numberBuilder.AppendFormat(numberChar)
                    numberIndex += 1

                Loop

                CommTK.OutputBizLog("ATAction", "Me.DoPrivateHandleCall(numberBuilder.ToString)", numberBuilder.ToString)
                Me.Invoke(New XL.Win.SubTransactionWithOneStringPara(AddressOf Me.DoPrivateHandleCall), numberBuilder.ToString)
            ElseIf modemReceiveString.Contains("RING") = True Then
                Me.Invoke(New XL.Win.SubTransaction(AddressOf Me.DoPrivateShowIncomingCallBalloon))
            End If

        End Sub

        Private Sub DoPrivateShowIncomingCallBalloon()
            If Utils.Decls.LAST_CALL_IN_PHONE_NUMBER.Length = 0 Then
                Return
            End If

            Dim balloonMessageBuilder As New LineStrBuilder
            balloonMessageBuilder.AppendLine(CommTK.GetTranslatedString("来电: ^ ,", Utils.Decls.LAST_CALL_IN_PHONE_NUMBER))
            balloonMessageBuilder.AppendLine(CommTK.GetTranslatedString("客户: ^ ,", Utils.Decls.LAST_CALL_IN_CLIENT_ROW_SE.CLIENT_NAME))
            balloonMessageBuilder.AppendLine(CommTK.GetTranslatedString("联系人: ^ ", Utils.Decls.LAST_CALL_IN_CLIENT_PERSON_ROW_SE.PERSON_NAME))

            Me.ShowNotifyBalloonMessage(ToolTipIcon.Info, balloonMessageBuilder.ToString)
        End Sub


        Private Sub DoPrivateHandleCall(ByVal phoneNumber As String)

            Dim result = Me.DoPublicCheckCallTransactionFormType
            Dim callType = result
            If result = 0 Then
                callType = RExpXAuto.Decls.CIVALUE_INCOMING_CALL_TYPE_POST_BOOKING
            End If

            If SysInfo.RegisterVersionLevel = VersionLevel.Trial AndAlso _
                Utils.Decls.UNTRANSACTED_INCOMING_POST_BOOKING_CALL_COUNT + Utils.Decls.UNTRANSACTED_INCOMING_QUERY_CALL_COUNT > 30 Then
                Me.ShowStatusMessage(StatusMessageIcon.Attention, RExpXService.Decls.MSG_STATUS_0007)
                Return
            End If

            Utils.Decls.CACHE_INCOMING_CALL_LIST.AddNewH_REXP_INCOMING_CALLRow( _
                   String.Empty, _
                   phoneNumber, _
                   callType, _
                   String.Empty, _
                   String.Empty, _
                   String.Empty, _
                   String.Empty, _
                   String.Empty, _
                   Guid.NewGuid.ToString, _
                   String.Empty, _
                   CommTK.GetSyncServerTime, _
                   String.Empty, _
                   String.Empty, _
                   String.Empty, _
                   String.Empty, _
                   SysInfo.ReadLocalSysInfo(RExpXService.Decls.LVN_LISTENING_PHONE_NUMBER), _
                   String.Empty, _
                   String.Empty, _
                   CommDecl.NULL_DATE, _
                   RExpXService.Decls.DEFAULT_CI_VALUE_INCOMING_CALL_TRANSACT_WAY_NONE, _
                   String.Empty)

            Utils.Decls.LAST_CALL_IN_PHONE_NUMBER = phoneNumber
            RExpXService.Facade.OpBizManage.FillClientPersonRowSEntityByCallNumber( _
                Utils.Decls.LAST_CALL_IN_PHONE_NUMBER, _
                Utils.Decls.LAST_CALL_IN_CLIENT_ROW_SE, _
                Utils.Decls.LAST_CALL_IN_CLIENT_PERSON_ROW_SE)

            If Utils.Decls.LAST_CALL_IN_CLIENT_ROW_SE.IsNull = True Then
                Utils.Decls.LAST_CALL_IN_CLIENT_ROW_SE.CLIENT_NAME = CommTK.GetTranslatedString("未知")
            End If
            If Utils.Decls.LAST_CALL_IN_CLIENT_PERSON_ROW_SE.IsNull = True Then
                Utils.Decls.LAST_CALL_IN_CLIENT_PERSON_ROW_SE.PERSON_NAME = CommTK.GetTranslatedString("未知")
            End If

            Utils.TK.OverwriteCacheIncomingCallList()
            Me._bizAgent.DoRequest(MainformAgent.Affairs.UpdateIncomingStatus, True)
            If result > 0 Then
                Me.DoPublicCallTransactionFormUpdateDisplay()
            End If

        End Sub

        Private Sub LinkLabel_IncomingCall_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkLabel_IncomingCall.Click
            If Me.LinkLabel_IncomingCall.Text = CommTK.GetTranslatedString(RExpXService.Decls.TEXT_0011) Then
                Dim configForm As New Manifest.M_08_00101(AddressOf Me.TransactRequest, 0)
                Me.AppendForm(configForm)
                Return
            End If


            Dim baseForm As Component.BaseForm
            Dim formIndex = Me.FindFormIndexByTitleLaunchCondition("业务操作-来电发货管理", RExpXService.S_02_00201.LCs.None.ToString, baseForm)
            If formIndex < 0 Then
                Dim transactForm As New Manifest.M_02_00201(AddressOf Me.TransactRequest, 0)
                Me.AppendForm(transactForm)
            End If
            Me.RestoreSkin()
        End Sub

        Private Sub SerialPort_Phone_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles SerialPort_Phone.Disposed

        End Sub

        Private Function DoPublicCallTransactionFormUpdateDisplay() As Integer

            If IsNothing(Me.SV_TRANSACTING_INCOMING_CALL_FORM) = False Then
                Me.SV_TRANSACTING_INCOMING_CALL_FORM.UpdateDisplay()
                Me.RestoreSkin()
            End If

        End Function

        Private Function DoPublicCheckCallTransactionFormType() As Integer


            'Dim postBookingTransactForm As New Manifest.M_02_00201(AddressOf Me.TransactRequest, 0)
            'Me.SV_TRANSACTING_INCOMING_CALL_FORM = TryCast(postBookingTransactForm, Component.BaseForm)
            Dim formIndex = Me.FindFormIndexByTitleLaunchCondition("业务操作-来电发货管理", RExpXService.S_02_00201.LCs.None.ToString, Me.SV_TRANSACTING_INCOMING_CALL_FORM)

            If formIndex >= 0 Then
                'Me.RestoreSkin()
                CommTK.OutputBizLog("ATAction", "Me.SetCurrentForm(TryCast(transactForm, Component.BaseForm))", "RExpXAuto.Decls.CIVALUE_INCOMING_CALL_TYPE_POST_BOOKING")
                Return RExpXAuto.Decls.CIVALUE_INCOMING_CALL_TYPE_POST_BOOKING
            End If

            'Dim qureyTransactForm As New Manifest.M_02_00301(AddressOf Me.TransactRequest, 0)
            'Me.SV_TRANSACTING_INCOMING_CALL_FORM = TryCast(qureyTransactForm, Component.BaseForm)
            formIndex = Me.FindFormIndexByTitleLaunchCondition("业务操作-来电查询管理", RExpXService.S_02_00201.LCs.None.ToString, Me.SV_TRANSACTING_INCOMING_CALL_FORM)
            'setFormResult = Me.SetCurrentForm(Me.SV_TRANSACTING_INCOMING_CALL_FORM)

            If formIndex >= 0 Then

                'Me.RestoreSkin()
                CommTK.OutputBizLog("ATAction", "Me.SetCurrentForm(TryCast(transactForm, Component.BaseForm))", "RExpXAuto.Decls.CIVALUE_INCOMING_CALL_TYPE_QUERY")
                Return RExpXAuto.Decls.CIVALUE_INCOMING_CALL_TYPE_QUERY

            End If

            'Me.SV_TRANSACTING_INCOMING_CALL_FORM = Nothing
            'Me.RestoreSkin()
            Return 0

        End Function


        'Private Sub Label_Clock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label_Clock.Click
        '    Dim phoneNumber = InputBox("CallNumber")
        '    Me.DoPrivateHandleCall(phoneNumber)

        'End Sub
    End Class

End Namespace

